package com.fullstack.landscape.editor.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fullstack.landscape.editor.service.SpotService;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;

/**
 * @author leven.chen
 * @project landscape-editor
 * @date 2019/4/20 20:15
 * @apiNote
 */
@RestController
@RequestMapping("/api/ueditor")
public class UeditorController {
    /**
     * logger
     */
    private static final Logger log = LoggerFactory.getLogger(UeditorController.class);

    private static final String ACTION_CONFIG = "config";

    private static final List<String> IMAGE_ACTIONS = Lists.newArrayList("uploadimage",
            "snapscreenimage", "catchimage");

    private final SpotService spotService;


    public UeditorController(SpotService spotService) {
        this.spotService = spotService;
    }

    @RequestMapping("/action")
    public ResponseEntity<String> handle(@RequestParam String action, @RequestParam(required = false) String callback,
                                         @RequestParam(value = "file", required = false) MultipartFile file,
                                         @RequestParam(required = false) String base64file) throws IOException {
        log.debug("action={}", action);
        String response = null;
        if (ACTION_CONFIG.equalsIgnoreCase(action)) {
            String config = this.getConfig();
            response = callback + "(" + config + ")";
        } else if (IMAGE_ACTIONS.contains(action)) {
            String originalFilename = file.getOriginalFilename();
            log.debug(originalFilename);
            String attachmentId = spotService.uploadImage(1, file);
            response = this.uploadImageResponse(attachmentId, originalFilename);
        } else if ("uploadscrawl".equalsIgnoreCase(action)) {
            log.debug(base64file);
            String originalFilename = "uploadscrawl-" + System.currentTimeMillis() + ".png";
            File tempFile = File.createTempFile("landspace-image", "temp");
            File newFile = Base64.decodeToFile(base64file, tempFile);
            String attachmentId = spotService.uploadImage(1, originalFilename, newFile);
            response = this.uploadImageResponse(attachmentId, originalFilename);
        }
        return new ResponseEntity<>(response, HttpStatus.OK);
    }


    /**
     * {
     * "state": "SUCCESS",
     * "url": "upload/demo.jpg",
     * "title": "demo.jpg",
     * "original": "demo.jpg"
     * }
     *
     * @return
     */
    private String uploadImageResponse(String url, String original) {
        JSONObject response = new JSONObject();
        response.put("state", "SUCCESS");
        response.put("url", "/api/attachment/" + url);
        response.put("title", "");
        response.put("original", original);
        return response.toString();
    }

    private String getConfig() throws IOException {
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        InputStream stream = resourceLoader.getResource("/ueditor/config.json").getInputStream();

        assert stream != null;
        BufferedReader buff = new BufferedReader(new InputStreamReader(stream));
        String temp;
        StringBuilder config = new StringBuilder();
        while ((temp = buff.readLine()) != null) {
            config.append(temp);
        }
        //把配置文件中的注释去掉
        String configStr = config.toString().replaceAll("/\\*[\\s\\S]*?\\*/", "");
        JSONObject jsonObject = JSONUtil.parseObj(configStr);
        return jsonObject.toString();
    }
}
